package com.loong.android.utils;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class DrawableUtils {

    public static Drawable from(Context context, int resId) {
        Resources resources = context.getResources();
        return new BitmapDrawable(resources, BitmapFactory.decodeResource(resources, resId));
    }

    public static Drawable from(Context context, Bitmap bitmap) {
        Resources resources = context.getResources();
        return new BitmapDrawable(resources, bitmap);
    }

    public static Drawable from(Context context, String filePath) {
        Resources resources = context.getResources();
        File file = new File(filePath);
        InputStream is = null;
        try {
            is = new BufferedInputStream(new FileInputStream(file));
            return new BitmapDrawable(resources, BitmapFactory.decodeStream(is));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (is != null) try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static Drawable from(Context context, byte[] bytes) {
        Resources resources = context.getResources();
        try {
            return new BitmapDrawable(resources, BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
